<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
	<head>
		<title>即时消息</title>

		<meta http-equiv="pragma" content="no-cache">
		<meta http-equiv="cache-control" content="no-cache">
		<meta http-equiv="expires" content="0">
		<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	</head>

	<body>
		<div id="messagerContent" class="dynamicPanel" style="height: 140px; display: none">
			<div name='messager' style='height: 85px; display: block'>
			</div>
			<div style="bottom: 10px; display: block">
				<a name="readFlag" href="#" rel='sortmsg' onClick="readFlag()"
					style="float: left; left: 5px; display: none; margin-left: 5px">确认</a>
				<!-- 
				<a name="readAllFlag" href="#" rel='sortmsg' onClick="readAllFlag()"
					style="float: left; left: 5px; display: none; margin-left: 5px">全部确认</a>
				 -->
				<a name="readMark" style="float: left; left: 5px; display: none; margin-left: 5px">已确认</a>
				<a name="rspsmsg" href="#" rel='sortmsg' onClick="responseMsg()"
					style="float: left; left: 5px; display: none; margin-left: 5px">回复</a>
				<a href="#" onClick="nextMsg()" name="nextmsg"
					style="float: right; right: 5px; display: none">下一条</a>
				<a name="premsg" href="#" onClick="preMsg()"
					style="float: right; margin-right: 5px; display: none">上一条</a>
			</div>
		</div>
		<div name="responseWin"></div>
		
		<div name="dynamicContent" style="height:100%;width:100%;display:none;overflow-x:hidden;overflow-y:hidden" >
			<div name="responeContent" style="height:80%;width:100%;overflow-y:auto">
				
			</div>
			<div name="inputArea" style="height:15%;width:100%">
				<textarea  name="inputText" style="height:90%;width:100%"></textarea>
				<input type="button" name="messageCommit" class="btn-style03" style="margin-bottom:10px;margin-left:10px;margin-right:10px" value="发送(Alt+S)" accesskey="s"/>
				<input type="button" name="moreMsg" class="btn-style03" value="更多...">
				提示:显示最新十条消息
			</div>
		</div>
		
		<div class="online-user" style="display:none">
				<div rel="online-content">
					<!-- 
					<select style="width:100px">
						<option>--请选择--</option>
					</select>
					 -->
				</div>
				<!-- 
				<div>
					<input name="submitOnlineUser" relname='' type="button" value="选择">
				</div>
				 -->
		</div>
		
		<div class="msgcenter-user" style="display:none">
			<div class="easyui-panel"  title="请选择用户" style="width:150px;height:80px;padding:10px;background:#fafafa;">
				<div>
					<select style="width:100px">
						<option>--请选择--</option>
					</select>
				</div>
				<div>
					<input name="submitMsgCenterUser" relname='' type="button" value="选择">
				</div>
			</div>
		</div>
	</body>
</html>
<script type="text/javascript">
	var currMsgId = 0;
	var msgs = new Array();
	var readPos = 0;
	var $messagerContent;
	var $dynamicContent;
	var isOpened = false;
	var isResponse = false;
	var msgShowTime = 5000;
	var $rpsWindow;
	$(document).ready(function(){
		// 提交消息，在消息窗口中显示这条消息，并将消息存入数据库
		$("input[name='messageCommit']").click(function(){
			var $inputTextArea = $dynamicContent.find("div[name='inputArea']").find("textarea[name='inputText']");
			var inputText = $inputTextArea.val();
			$inputTextArea.val("");
			if(jQuery.trim(inputText) == ''){
				return;
			}
			var date=new Date();
			var year=date.getFullYear();//获取年份
			var month=date.getMonth()+1;
			if(month < 10){
				month = "0"+month;
			}
			var day=date.getDate();
			if(day < 10){
				day = "0"+day;
			}
			var hour=date.getHours();
			if(hour < 10){
				hour = "0"+hour;
			}
			var minute=date.getMinutes();
			if(minute < 10){
				minute = "0" + minute;
			}
			var seconds = date.getSeconds();
			if(seconds < 10){
				seconds = "0" + seconds;
			}
			var msgId = date.getTime();
			var timeStr = year+"-"+month+"-"+day+"&nbsp;&nbsp;"+hour+":"+minute+":"+seconds;
			addMsg(msgId,timeStr,'当前用户',inputText,true);
		});
		
		$("input[name='submitMsgCenterUser']").click(function(){
			var receiver = $(this).parent().parent().find("select option:selected").val();
			if(receiver == ''){
				return;
			}
			onLineMsgShow(loginId,receiver);
		});
	})
	// 显示消息
	var showMessager = function(){
		var msgInfo = msgs.shift();
		$messagerContent = $("#messagerContent").clone(true);
		if(msgInfo=='undifined'){
			// 如果未定义，就证明是自动获取消息时获取的消息为空，不需要显示message对话框
			return;
		}else{
			// 置第一条信息为当前显示
			readPos = 0;
			currMsgId = msgInfo.MSG_ID;
			// 显示回复和已读按钮，当第一条信息MSG_ID不为空时，应该显示这两个按钮
			if(currMsgId != ""){
				$messagerContent.find("a[rel='sortmsg']").show();
				msgs.unshift(msgInfo);
			}
		}
        if(msgs !=null && msgs.length > 1){
        	$messagerContent.find("a[name='nextmsg']").show();
        }
       $.messager.show({
           id:'msg',
           title:'消息',  
           msg:'',
           timeout:msgShowTime,
           showType:'slide',
           height:150,
           width:250,
           modal:true,
           openShow:function(){
           		isOpened = true;
           },
           closeShow:function(){
           		// 如果是手动执行，则不需要设置超时时间重新加载数据
           		// 如果没有指定要单次加载，默认间隔毫秒重新加载
           		if(messageSetting.display_type == '1'){
           			setTimeout("loadUnreadMsg('auto')", messageSetting.display_interval*60000);
           		}
           		isOpened = false;
           }
       });

        if($("body > div .messager-body").length>1){
            win = $("body > div .messager-body[id=msg]");
            win.window("window").css({
                'bottom' : '220px',
                'right' : '10px'
            })
        }
       $(".panel .messager-body").append($messagerContent);
       $messagerContent.show();
       // 将消息显示在内容区域
       resetMsg();
   } 
   // 重置消息框中显示的消息内容
   var resetMsg = function(){
		var title = "来自:";
		var content = msgs[readPos].MSG_CONTENT;
		if(content.length > 60){
			content = content.substring(0,60)+"...<a style='color:red;font-size:12'>更多<a/>"
		}
		var responseId = msgs[readPos].RESPONSE_ID;
		var receiver = msgs[readPos].MSG_RECEIVER;
		var sender = msgs[readPos].MSG_SENDER;
		var onlineId = msgs[readPos].ONLINE_ID;
		title += sender;
		currMsgId = msgs[readPos].MSG_ID;
		toggleReadBtn(currMsgId);
		$messagerContent.parent().parent().find(".panel-title").html(title);
		$messagerContent.find("div[name='messager']")
					.attr("msgid",currMsgId)
					.attr("responseid",responseId)
					.attr("receiver",receiver)
					.attr("sender",sender)
					.attr("onlineid",onlineId)
					.html("").html(content);
	}
   
	/**
     * 消息中心
     * 加载未读消息
     */
    function loadUnreadMsg(loadType){
    	// 如果已经打开，则不必打开对话框
    	if(isOpened||isResponse){
    		return ;
    	}
    	// 重新初始化参数
    	readPos = 0;
   		if(msgs!=null && msgs.length > 0){
   			// 清空数组，重新加载数据
   			msgs.length = 0;
   		}
        $.ajax({
            url: 'loadUnreadMessages.do',
            type: "POST",
            data: 'MSG_ID='+currMsgId,
            cache: false,
            error:function(){
                alert('连接服务器失败，请重新登录！');
            },
            success: function(msg){
                var json = eval(msg);
                if(json.length>0){
                    //如果有消息，将消息放入msgs数组中
                    $.each(json, function(i,item){
                        msgs.push(item);
                    });
                    //显示消息提示窗口
                    //如果是首次展示消息，展示第一条，否则只更新消息盒子上面的消息总条数
                    showMessager();
                }else{
                	if(loadType != 'auto'){
                		var sysObj = new Object();
                		sysObj.MSG_ID = "";
                		sysObj.MSG_CONTENT = "无消息";
                		sysObj.MSG_RECEIVER = "系统提示";
                		msgs.push(sysObj);
                		showMessager();
                	}
                }
            }
        });
    }
    // 单击下一条消息
    var nextMsg = function(){
    	// 如果当前位置小于msgs的长度
    	// 首先要显示上一条的按钮
    	// 加载位置+1的消息
    	readPos ++;
		if(readPos == msgs.length-1){
			$messagerContent.find("a[name='premsg']").show();
			$messagerContent.find("a[name='nextmsg']").hide();
		}else{
			$messagerContent.find("a[name='premsg']").show();
			$messagerContent.find("a[name='nextmsg']").show();
		}
		resetMsg();
	}
	// 单击确认按钮时，将消息置为已读状态
	var readFlag = function(){
		$.ajax({
			url:"readMessage.do",
			type:"post",
			data:"MSG_ID="+currMsgId,
			success:function(msg){
				if(msg == 'true'){
					msgs[readPos].READ_CONFIRM = true;
					//$.messager.alert("确认成功","已确认该消息已经接收!");
					toggleReadBtn(currMsgId);
					//nextMsg();
					currMsgId="";
					return;
				}
				$.messager.alert('确认失败',msg);
			}
		})
	}
	/*
	var readAllFlag = function(){
		var msgIdArray = new Array();
		$.each(msgs,function(idx,obj){
			msgIdArray.push(obj.MSG_ID);
		});
		currMsgId = msgIdArray.join(",");
		readFlag();
	}*/
	// 上一条消息
	var preMsg = function(){
		readPos --;
		if(readPos == 0){
			$messagerContent.find("a[name='premsg']").hide();
		}
		$messagerContent.find("a[name='nextmsg']").show();
		resetMsg();
	}
	// 置消息窗口中回复按钮与确认按钮显示状态
	var toggleReadBtn = function(msgIds){
		if(msgs[readPos].READ_CONFIRM){
			$messagerContent.find("a[name='readMark']").show();
			$messagerContent.find("a[name='readFlag']").hide();
		}else{
			$messagerContent.find("a[name='readMark']").hide();
			$messagerContent.find("a[name='readFlag']").show();
		}
	}
	// 封装一个会话包含的所有信息
	var responseMsg = function(){
		// 加载这条消息的内容
		var $messager = $messagerContent.find("div[name='messager']");
		var responseId = $messager.attr("responseid");
		var sender = $messager.attr("sender");
		var receiver = $messager.attr("receiver");
		var onlineId = $messager.attr("onlineid");
		currMsgId = $messager.attr("msgid");
		if(responseId == '' || responseId == 'null' || responseId == null){
			$.messager.alert('此消息不能回复','对不起，此消息不能回复!');
			return;
		}
		// 将需要回复的信息状态更新为已读取
		readFlag();
		loadResponseMsg(responseId);
		var interval = setInterval('loadResponseMsg("'+responseId+'")',60000);
		$dynamicContent = $("div[name='dynamicContent']").clone(true);
		$dynamicContent.attr("msgid",currMsgId)
						.attr("responseid",responseId)
						.attr("receiver",receiver)
						.attr("sender",sender)
						.attr("onlineid",onlineId);
						;
		$rpsWindow = $("div[name='responseWin']").empty().append($dynamicContent.show()).window({
			title:"消息",
		    width:600,  
		    height:400,
		    modal:true,
		    onBeforeClose:function(){
		    	$(this).empty();
		    	clearInterval(interval);
		    	isResponse = false;
		    	if(messageSetting.display_type == '1'){
			    	// 如果没有指定要单次加载，默认间隔毫秒重新加载
	           		setTimeout("loadUnreadMsg('auto')", messageSetting.display_interval*60000);
           		}
		    },
		    onBeforeOpen:function(){
		    	isResponse = true;
		    }
		});
	}
	// 根据responseId加载消息，
	var loadResponseMsg = function(responseId){
		$.ajax({
			url:"loadMsgByResponseId.do",
			type:"post",
			data:"responseId="+responseId,
			success:function(msg){
				if(msg.length > 0){
					$.each(msg,function(idx,obj){
						addMsg(obj.MSG_ID,obj.SEND_TIME,obj.MSG_SENDER,obj.MSG_CONTENT,false);
					})
				}
			}
		});
	}
	// 在消息窗口中增加消息条目
	var addMsg = function(msgId,time,user,content,newFlag){
		var $responeContent = $dynamicContent.find("div[name='responeContent']");
		var responseId = $dynamicContent.attr("responseid");
		var onlineId = $dynamicContent.attr("onlineid");
		if(newFlag){
			// 把以前的发送者作为接受者,以前的接收者作为发送者保存到库中
			var recevier = $dynamicContent.attr("sender");
			var sender = $dynamicContent.attr("receiver");
			user = sender;
			$.ajax({
				type:"post",
				url:"saveMsg.do",
				data:"msg.MSG_ID="+msgId+"&msg.MSG_SENDER="+sender+"&msg.MSG_CONTENT="+content+"&msg.RESPONSE_ID="+responseId+"&msg.MSG_RECEIVER="+recevier+"&msg.ONLINE_ID="+onlineId,
				success:function(msg){
					
				}
			})
		}
		var hasPutMsg = false;
		var $ulList = $responeContent.find("ul");
		// 获取下面的所有ul标签，查看此消息是否已经添加，如果添加了，就不再添加
		$ulList.each(function(idx,obj){
			if(($ulList.length - 20) > idx){
				$(this).hide();
			}
			if($(this).attr("msgId") == msgId){
				hasPutMsg = true;
			}
		});
		if(!hasPutMsg){
			var $ulArea = $("<ul></ul>").attr('msgId',msgId);
			var $liTitle = $("<li style='color:blue'>"+user+"&nbsp;&nbsp;&nbsp;&nbsp;"+time+"<li>");
			var $liContent = $("<li>&nbsp;&nbsp;&nbsp;&nbsp;"+content+"</li>");
			$ulArea.append($liTitle).append($liContent);
			$responeContent.append($ulArea);
			$responeContent.scrollTop($responeContent.height()+$responeContent.offset().top);
		}
	}
	
	//在线消息穿窗口显示,传入发送人与接收人
	var onLineMsgShow = function(sender,receiver){
		// 在线客服人员作为接受者，用户作为发送者
		var date = new Date();
		if(sender == 'admin'){
			onlineId = receiver+"-"+sender;
		}else{
			onlineId = sender+"-"+receiver;
		}
		openOnlineMsgWin(sender,receiver);
	}
	
	// 打开在线消息窗口
	var openOnlineMsgWin = function(sender,receiver){
		var refreshFlag;
		$dynamicContent = $("div[name='dynamicContent']").clone(true);
		// 在线客服需要有两个属性，根据这两个属性获取，模拟一条相反的消息，因此现在的发送者作为消息的接收者使用
		$dynamicContent.attr("responseid",onlineId)
						.attr("onlineid",onlineId)
						.attr("receiver",sender)
						.attr("sender",receiver);
		$("div[name='responseWin']").append($dynamicContent.show()).window({
			title:receiver,
		    width:600,  
		    height:400,
		    modal:true,
		    onBeforeClose:function(){
		    	$(this).empty();
		    	isResponse = false;
		    	if(messageSetting.display_type == '1'){
			    	// 如果没有指定要单次加载，默认间隔毫秒重新加载
	           		setTimeout("loadUnreadMsg('auto')", messageSetting.display_interval*60000);
           		}
           		clearInterval(refreshFlag);
		    },
		    onBeforeOpen:function(){
		    	isResponse = true;
		    }
		});
		refreshOnlineMsg(onlineId);//加载历史消息
		refreshFlag = setInterval("refreshOnlineMsg('"+onlineId+"')",60000);
	}
	// 刷新在线消息
	var refreshOnlineMsg = function(onlineId){
		$.ajax({
			url:"loadOnlineServerMsg.do?msg.ONLINE_ID="+onlineId,
			type:"post",
			success:function(data){
				//var addMsg = function(msgId,time,user,content,newFlag){
				$.each(data,function(idx,msgObj){
					addMsg(msgObj.MSG_ID,msgObj.SEND_TIME,msgObj.MSG_SENDER,msgObj.MSG_CONTENT,false)
				});
			}
		})
	}
	
</script>
